package com.shop.shopserver.service.impl;

import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.fastjson.JSONPObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shop.shopcommon.context.SecurityContext;
import com.shop.shopcommon.exception.Base.UserNotLoginException;
import com.shop.shopcommon.template.AiReturn;
import com.shop.shopcommon.template.Request;
import com.shop.shoppojo.dto.AiChatDTO;
import com.shop.shoppojo.entity.MedicalRecord;
import com.shop.shoppojo.vo.AiChatVO;
import com.shop.shoppojo.vo.DailyRecommendVO;
import com.shop.shopserver.mapper.MedicalRecordMapper;
import com.shop.shopserver.sender.TongyiQianwenSender;
import com.shop.shopserver.service.AiChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.shop.shopcommon.constant.MessageConstant.USER_NOT_LOGIN;

@Service
public class AiChatServiceImpl implements AiChatService {
    @Autowired
    private MedicalRecordMapper medicalRecordMapper;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private TongyiQianwenSender tongyiQianwenSender;
    /**
     * ai每日推荐
     */
    public DailyRecommendVO aiDailyRecommend() throws JsonProcessingException, NoApiKeyException, InputRequiredException {
        // 获取用户病例
        MedicalRecord medicalRecord = getMedicalRecord();
        // 将用户病例对象转为字符串
        String medicalRecordString = objectMapper.writeValueAsString(medicalRecord);
        // 获取ai返回模板
        String aiReturn = AiReturn.RECENT_RECOMMEND_TEMPLATE;
        // 获取请求模板字符串
        String template = Request.RECOMMEND_TEMPLATE;
        // 将用户病例字符串消息和ai返回模板字符串拼接到请求模板字符串中
        String request = template.replace("#{medicalRecord}", medicalRecordString);
        request = request.replace("#{aiReturn}", aiReturn);
        // 发送请求到ai
        GenerationResult result = tongyiQianwenSender.callWithMessage(request);
        // 处理结果并返回
        String content = result.getOutput().getChoices().get(0).getMessage().getContent();
        return objectMapper.readValue(content, DailyRecommendVO.class);
    }

    /**
     * 保存用户病例
     * @param medicalRecord
     */
    @Override
    public void saveMedicalRecord(MedicalRecord medicalRecord) {
        // 获取用户id
        Long userId = SecurityContext.getUserId();
        if (userId == null) {
            throw new UserNotLoginException(USER_NOT_LOGIN);
        }

        // 组织用户病例对象
        medicalRecord.setUserId(userId);

        // 更新或插入用户病例对象
        LambdaUpdateWrapper<MedicalRecord> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(MedicalRecord::getUserId, userId);
        // 判断是否已存在该用户的病例记录
        if (medicalRecordMapper.exists(wrapper)) {
            // 如果存在，则更新
            medicalRecordMapper.update(medicalRecord, wrapper);
        } else {
            // 如果不存在，则插入
            medicalRecordMapper.insert(medicalRecord);
        }
    }

    /**
     * 获取用户健康信息
     * @return
     */
    @Override
    public MedicalRecord getMedicalRecord() {
        // 获取用户id
        Long userId = SecurityContext.getUserId();
        if (userId == null) {
//            throw new UserNotLoginException(USER_NOT_LOGIN);
            return null;
        }
        // 获取用户病例对象
        return medicalRecordMapper.selectOne(new LambdaQueryWrapper<MedicalRecord>().eq(MedicalRecord::getUserId, userId));
    }

    /**
     * 获取健康咨询
     * @return
     */
    @Override
    public AiChatVO aiHealthInquiry(AiChatDTO aiChatDTO) throws JsonProcessingException, NoApiKeyException, InputRequiredException {
        // 获取用户病例
        MedicalRecord medicalRecord = getMedicalRecord();
        // 将用户病例对象转为字符串
        String medicalRecordString = objectMapper.writeValueAsString(medicalRecord);
        // 获取ai返回模板
        String aiReturn = AiReturn.HEALTH_INQUIRY_TEMPLATE;
        // 获取请求模板字符串
        String template = Request.HEALTH_INQUIRY_TEMPLATE;
        // 将用户病例字符串消息和ai返回模板字符串拼接到请求模板字符串中
        String request = template.replace("#{medicalRecord}", medicalRecordString);
        request = request.replace("#{aiReturn}", aiReturn);
        // 发送请求到ai
        GenerationResult result = tongyiQianwenSender.callWithMessage(request);
        // 处理结果并返回
        String content = result.getOutput().getChoices().get(0).getMessage().getContent();
        System.out.println(content);
        return objectMapper.readValue(content, AiChatVO.class);
    }

    /**
     * 对话框对话
     * @param aiChatDTO
     * @return
     */
    @Override
    public AiChatVO aiDialogBoxChat(AiChatDTO aiChatDTO) throws JsonProcessingException, NoApiKeyException, InputRequiredException {
        // 获取用户病例
        MedicalRecord medicalRecord = getMedicalRecord();
        // 将用户病例对象转为字符串
        String medicalRecordString = objectMapper.writeValueAsString(medicalRecord);
        // 获取用户问题
        String question = aiChatDTO.getMessage();
        // 获取ai返回模板
        String aiReturn = AiReturn.HEALTH_INQUIRY_TEMPLATE;
        // 获取请求模板字符串
        String template = Request.DIALOG_BOX_TEMPLATE;
        // 将用户病例字符串消息和ai返回模板字符串拼接到请求模板字符串中
        String request = template.replace("#{medicalRecord}", medicalRecordString);
        request = request.replace("#{aiReturn}", aiReturn);
        request = request.replace("#{question}", question);
        // 发送请求到ai
        GenerationResult result = tongyiQianwenSender.callWithMessage(request);
        // 处理结果并返回
        String content = result.getOutput().getChoices().get(0).getMessage().getContent();
        System.out.println(content);
        return objectMapper.readValue(content, AiChatVO.class);
    }
}
